<?php


namespace app\common\cachemodel\lucky;


use app\common\cachemodel\ZlUserVip;
use app\common\model\BaseCache;
use think\Db;
use think\Log;
use XznsTools\cache\CacheManage;

class AppUserAdornInfo extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_user_adorn_info';

    protected $cacheModel = 'lucky_planet.user_adorn';

    /**
     * 获取 用户 拥有的装扮列表
     * @param int $uid
     * @return array
     * @throws \Exception
     */
    public function getUserHasAdornLists(int $uid)
    {
        $nowTime = time();
        $adronDataIds = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage(-1)
            ->setSort('asc')
            ->getListPageDataIds(function ($ids = [], $isCache = true, $sortType = 'desc') use ($uid)
            {
                try
                {
                    $t = time();
                    $ids = Db::table('wechat_backup_07_18_14_43_00.app_user_lucky_change_record')->where(['uid' => $uid, 'exchange_id' => ['>', 0]])->where('expire_time', '>', $t)->order('id asc')->column('id');
                    $rd = [];
                    foreach ($ids as $id)
                    {
                        $rd[$id] = ['id' => $id];
                    }

                    return $rd;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'id', 0);
        $adronDatas = [];
        $exchangeDatas = [];
        if ($adronDataIds['data'])
        {   // 获取用户 拥有的装扮
            $adronDatas = (new AppUserLuckyChangeRecord())->batchGetInfoByIds(array_keys($adronDataIds['data']), ['id', 'expire_time', 'exchange_id']);
            $exchangeIds = array_column($adronDatas, 'exchange_id');
            $exchangeDatas = (new AppLuckyExchange())->batchGetInfoByIds($exchangeIds, ['type', 'name', 'photo']);
        }

        $resData = [
            'adorn_list' => [
                [
                    'id' => 0,
                    'title' => '无头像框',
                    'img' => '/test/lucky_star/adorn-avatar-0.png',
                    'des' => '默认',
                    'is_selected' => 0,
                    'reality_img' => '',
                ]
            ],
            'tag_list' => [
                [
                    'id' => 0,
                    'title' => '默认标签',
                    'img' => '/test/lucky_star/adorn-tag-0.png',
                    'des' => '默认',
                    'is_selected' => 0,
                    'reality_img' => '',
                ]
            ],
            'badge_list' => [],
        ];
        // 获取用户vip等级信息
        $vipInfo = (new ZlUserVip())->getInfoById($uid);
        $vipLevel = ($vipInfo && isset($vipInfo['is_valid']) && $vipInfo['is_valid'] == 1) ? (int)$vipInfo['vip_level'] : 0;
        if ($vipLevel > 0)
        {
            $vipEndTime = date('Y-m-d H:i', $vipInfo['end_time']);
            $luckyAdornConfig = config('lucky_adorn');
            $resData['adorn_list'][] = [
                'id' => $luckyAdornConfig['vip_adorn'],
                'title' => '会员头像框',
                'img' => $luckyAdornConfig['adorn_list'][$luckyAdornConfig['vip_adorn']]['img'],
                'des' => '有效期' . $vipEndTime,
                'is_selected' => 0,
                'reality_img' => $luckyAdornConfig['adorn_list'][$luckyAdornConfig['vip_adorn']]['reality_img'],
            ];

            $resData['badge_list'][] = [
                'id' => $luckyAdornConfig['vip_badge'],
                'title' => '会员徽章',
                'img' => str_replace('[LEVEL]', $vipLevel, $luckyAdornConfig['adorn_list'][$luckyAdornConfig['vip_badge']]['img']),
                'des' => '有效期' . $vipEndTime,
                'is_selected' => 0,
                'reality_img' => str_replace('[LEVEL]', $vipLevel, $luckyAdornConfig['adorn_list'][$luckyAdornConfig['vip_badge']]['reality_img']),
            ];

        }
        // 添加拥有的装扮
        foreach ($adronDatas as $adronDataItem)
        {
            if ($nowTime > $adronDataItem['expire_time'])
            {   // 已过期
                $this->userAdornDel($uid, $adronDataItem['id']);
                continue;
            }
            $exchangeItem = $exchangeDatas[$adronDataItem['exchange_id']];
            $d = [
                'id' => $adronDataItem['id'],
                'title' => $exchangeItem['name'],
                'img' => $exchangeItem['photo']['img_list']['url'],
                'des' => '有效期' . date('Y-m-d H:i', $adronDataItem['expire_time']),
                'is_selected' => 0,
                'reality_img' => $exchangeItem['photo']['img']['url'],
            ];
            switch ($exchangeDatas[$adronDataItem['exchange_id']]['type'])
            {
                case 1:
                    $resData['adorn_list'][] = $d;
                    break;
                case 2:
                    $resData['badge_list'][] = $d;
                    break;
                case 3:
                    $resData['tag_list'][] = $d;
                    break;
            }
        }
        // 获取用户当前 使用的 装扮
        $userAdronInfo = $this->getUserAdornInfo($uid);
        // 头像框
        foreach ($resData['adorn_list'] as $key => $adronitem)
        {
            if ($userAdronInfo['adorn_info']['id'] == $adronitem['id'])
            {
                $resData['adorn_list'][$key]['is_selected'] = 1;
                break;
            }
        }
        // 标签
        foreach ($resData['tag_list'] as $key => $tagItem)
        {
            if ($userAdronInfo['tag_info']['id'] == $tagItem['id'])
            {
                $resData['tag_list'][$key]['is_selected'] = 1;
                break;
            }
        }
        $badgeIds = $userAdronInfo['badge_info'] ? array_column($userAdronInfo['badge_info'], 'id') : [];
        $resData['badge'] = $userAdronInfo['badge_info'] ? array_column($userAdronInfo['badge_info'], 'reality_img') : [];
        // 徽章
        if ($badgeIds)
        {
            foreach ($resData['badge_list'] as $key => $badgeItem)
            {
                if (in_array($badgeItem['id'], $badgeIds, true))
                {
                    $resData['badge_list'][$key]['is_selected'] = 1;
                }
            }
        }

        return $resData;
    }

    /**
     * 判断用户 是否已经拥有当前装扮
     * @param int $uid
     * @param int $exchangeId
     * @return bool true=>已经拥有   false=>未拥有
     * @throws \Exception
     */
    public function UserIsHasAdorns(int $uid, int $exchangeId)
    {
        $adronDatas = $this->getUserAdorns($uid);

        $exchangeIds = array_column($adronDatas, 'exchange_id');

        return in_array($exchangeId, $exchangeIds, true);
    }

    /**
     * 获取用户 拥有的装扮 ID【可兑换的装扮里面的 ID】
     * @param int $uid
     * @return array
     * @throws \Exception
     */
    public function getUserAdorns(int $uid)
    {
        $adronDataIds = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage(-1)
            ->setSort('asc')
            ->getListPageDataIds(function ($ids = [], $isCache = true, $sortType = 'desc') use ($uid)
            {
                try
                {
                    $t = time();
                    $ids = Db::table('wechat_backup_07_18_14_43_00.app_user_lucky_change_record')->where(['uid' => $uid, 'exchange_id' => ['>', 0]])->where('expire_time', '>', $t)->order('id asc')->column('id');
                    $rd = [];
                    foreach ($ids as $id)
                    {
                        $rd[$id] = ['id' => $id];
                    }

                    return $rd;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'id', 0);

        $adronDatas = [];
        if ($adronDataIds['data'])
        {   // 获取用户 拥有的装扮
            $adronDatas = (new AppUserLuckyChangeRecord())->batchGetInfoByIds(array_keys($adronDataIds['data']), ['id', 'expire_time', 'exchange_id']);
        }

        return $adronDatas;
    }

    /**
     * 用户装扮增加
     * @param int $uid
     * @param int $id
     * @throws \Exception
     */
    public function userAdornAdd(int $uid, int $id)
    {
        $this->listDataAdd($uid, [$id => $id]);
    }

    /**
     * 用户装扮减少
     * @param int $uid
     * @param int $id
     * @throws \Exception
     */
    public function userAdornDel(int $uid, int $id)
    {
        $this->listDataDel($uid, [$id]);
    }

    /**
     * 获取用户 当前的装扮信息
     * @param int $uid
     * @param int $userType 用户类型 0=>普通用户 ，1=>官方, 2=>女神,3=>用户来稿
     * @return array
     * @throws \Exception
     */
    public function getUserAdornInfo(int $uid, int $userType = 0)
    {
        $resData = [
            'adorn_info' => [
                'reality_img' => '',
                'id' => 0,
            ],
            // 标签信息
            'tag_info' => [
                'reality_img' => '',
                'id' => 0,
            ],
            // 徽章信息
            'badge_info' => [],
        ];

        $nowTime = time();
        $luckyAdornConfig = config('lucky_adorn');

        switch ($userType)
        {
            case 1: // 官方
                // 官方用户 强制 官方头像框
                $resData['adorn_info'] = [
                    'id' => $luckyAdornConfig['adorn_flag1'],
                    // 'img' => $luckyAdornConfig['adorn_list'][$luckyAdornConfig['adorn_flag1']]['img'],
                    'reality_img' => $luckyAdornConfig['adorn_list'][$luckyAdornConfig['adorn_flag1']]['reality_img'],
                ];
                $resData['tag_info'] = [
                    'id' => $luckyAdornConfig['tag_flag1'],
                    // 'img' => $luckyAdornConfig['adorn_list'][$luckyAdornConfig['tag_flag1']]['img'],
                    'reality_img' => $luckyAdornConfig['adorn_list'][$luckyAdornConfig['tag_flag1']]['reality_img'],
                ];
                return $resData;
            case 2: // 女神
                $resData['adorn_info'] = [
                    'id' => $luckyAdornConfig['adorn_flag2'],
                    // 'img' => $luckyAdornConfig['adorn_list'][$luckyAdornConfig['adorn_flag2']]['img'],
                    'reality_img' => $luckyAdornConfig['adorn_list'][$luckyAdornConfig['adorn_flag2']]['reality_img'],
                ];
                $resData['tag_info'] = [
                    'id' => $luckyAdornConfig['tag_flag1'],
                    // 'img' => $luckyAdornConfig['adorn_list'][$luckyAdornConfig['tag_flag1']]['img'],
                    'reality_img' => $luckyAdornConfig['adorn_list'][$luckyAdornConfig['tag_flag1']]['reality_img'],
                ];
                return $resData;
            case 3://用户来稿
                $resData['adorn_info'] = [
                    'id' => 0,
                    // 'img' => $luckyAdornConfig['adorn_list'][$luckyAdornConfig['adorn_flag2']]['img'],
                    'reality_img' => '',
                ];
                $resData['tag_info'] = [
                    'id' => $luckyAdornConfig['tag_flag3'],
                    // 'img' => $luckyAdornConfig['adorn_list'][$luckyAdornConfig['tag_flag1']]['img'],
                    'reality_img' => $luckyAdornConfig['adorn_list'][$luckyAdornConfig['tag_flag3']]['reality_img'],
                ];
                return $resData;
            default:
        }

        $userAdornInfo = $this->getUserAdornConfig($uid);
        // 获取用户vip等级信息
        $vipLevel = (new ZlUserVip())->getUserVipLevel($uid);
        $appLuckyExchangeModel = new AppLuckyExchange();
        try
        {
            if ($userAdornInfo)
            {   // 使用过装扮
                $adornInfo = $userAdornInfo['adorn_info'] ? json_decode($userAdornInfo['adorn_info'], true) : ['id' => 0, 'exId' => 0, 'expire_time' => 0];
                if ($adornInfo['id'] > 0)
                {
                    if ($adornInfo['id'] === $luckyAdornConfig['vip_adorn'])
                    {   // vip 头像框
                        if ($vipLevel > 0)
                        {
                            $resData['adorn_info'] = [
                                'id' => $luckyAdornConfig['vip_adorn'],
                                // 'img' => $luckyAdornConfig['adorn_list'][$luckyAdornConfig['vip_adorn']]['img'],
                                'reality_img' => $luckyAdornConfig['adorn_list'][$luckyAdornConfig['vip_adorn']]['reality_img'],
                            ];
                        }
                    } else
                    {   // 其他头像框
                        if ($nowTime < $adornInfo['expire_time'])
                        {   // 头像框 未过期
                            $adorn = $appLuckyExchangeModel->getInfoById($adornInfo['exId'], ['photo']);
                            $resData['adorn_info'] = [
                                'id' => $adornInfo['id'],
                                // 'img' => $adornData['img_list']['url'],
                                'reality_img' => $adorn['photo']['img']['url'],
                            ];
                        }
                    }
                }
                $tagInfo = $userAdornInfo['tag_info'] ? json_decode($userAdornInfo['tag_info'], true) : ['id' => 0, 'exId' => 0, 'expire_time' => 0];
                if ($tagInfo > 0)
                {
                    if ($nowTime < $tagInfo['expire_time'])
                    {   // 标签 未过期
                        $adorn = $appLuckyExchangeModel->getInfoById($tagInfo['exId'], ['photo']);
                        $resData['tag_info'] = [
                            'id' => $tagInfo['id'],
                            // 'img' => $adornData['img_list']['url'],
                            'reality_img' => $adorn['photo']['img']['url'],
                        ];
                    }
                }
                $badgeInfo = $userAdornInfo['badge_info'] ? json_decode($userAdornInfo['badge_info'], true) : [];
                foreach ($badgeInfo as $badgeItem)
                {
                    if ($badgeItem['id'] === $luckyAdornConfig['vip_badge'])
                    {
                        if ($vipLevel > 0)
                        {
                            $resData['badge_info'][] = [
                                'id' => $luckyAdornConfig['vip_badge'],
                                // 'img' => str_replace('[LEVEL]', $vipLevel, $luckyAdornConfig['adorn_list'][$luckyAdornConfig['vip_badge']]['img']),
                                'reality_img' => str_replace('[LEVEL]', $vipLevel, $luckyAdornConfig['adorn_list'][$luckyAdornConfig['vip_badge']]['reality_img']),
                            ];
                        }
                    } else
                    {
                        if ($nowTime < $badgeItem['expire_time'])
                        {   // 徽章 未过期
                            $adorn = $appLuckyExchangeModel->getInfoById($badgeItem['exId'], ['photo']);
                            $resData['badge_info'][] = [
                                'id' => $badgeItem['id'],
                                // 'img' => $adornData['img_list']['url'],
                                'reality_img' => $adorn['photo']['img']['url'],
                            ];
                        }
                    }
                }
            } else
            {   // 还未使用过装扮 功能
                if ($vipLevel > 0)
                {
                    $resData['adorn_info'] = [
                        'id' => $luckyAdornConfig['vip_adorn'],
                        // 'img' => $luckyAdornConfig['adorn_list'][$luckyAdornConfig['vip_adorn']]['img'],
                        'reality_img' => $luckyAdornConfig['adorn_list'][$luckyAdornConfig['vip_adorn']]['reality_img'],
                    ];

                    $resData['badge_info'][] = [
                        'id' => $luckyAdornConfig['vip_badge'],
                        // 'img' => str_replace('[LEVEL]', $vipLevel, $luckyAdornConfig['adorn_list'][$luckyAdornConfig['vip_badge']]['img']),
                        'reality_img' => str_replace('[LEVEL]', $vipLevel, $luckyAdornConfig['adorn_list'][$luckyAdornConfig['vip_badge']]['reality_img']),
                    ];
                }
            }
        }
        catch (\Exception $e)
        {
            Log::write('获取用户装扮信息异常：AppUserAdornInfo=>getUserAdornInfo():' . $e->getMessage() . ';FILE:' . $e->getFile() . ';LINE:' . $e->getLine() . ';', 'error', true);
        }

        return $resData;
    }

    /**
     * 获取用户当前装扮配置
     * @param int $uid
     * @return array|bool|mixed|string
     * @throws \Exception
     */
    public function getUserAdornConfig(int $uid)
    {
        return CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setCacheKeyDetail('adorn_details', $uid)->getDataAndSet(function () use ($uid)
        {
            try
            {
                return $this->where('uid', $uid)->field('id,adorn_info,tag_info,badge_info,create_time,update_time')->findOrFail()->toArray();
            }
            catch (\Exception $e)
            {
                return [];
            }
        }, [], 'adorn_details');
    }

    /**
     * 保存用户装扮信息 // ['id' => 0, 'exId' => 0, 'expire_time' => 0]
     * @param int $id
     * @param int $uid
     * @param array $config ['adorn_info'=>"['id' => 0, 'exId' => 0, 'expire_time' => 0]"]
     * @return bool
     */
    public function SaveUserAdornConfig(int $id, int $uid, array $config)
    {
        try
        {
            $nowTime = time();
            if ($id)
            {
                $config['update_time'] = $nowTime;
                $this->where(['id' => $id])->update($config);

                CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setCacheKeyDetail('adorn_details', $uid)->setCache($config, 'adorn_details');
            } else
            {
                $this->save([
                    'uid' => $uid,
                    'adorn_info' => $config['adorn_info'],
                    'tag_info' => $config['tag_info'],
                    'badge_info' => $config['badge_info'],
                    'create_time' => $nowTime,
                    'update_time' => 0,
                ]);
            }
        }
        catch (\Exception $e)
        {
            Log::write('装扮保存 AppUserAdornInfo model => SaveUserAdornConfig()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');

            return false;
        }

        return true;
    }
}
